package com.ruoyi.game.schedule;

import java.util.*;
import javax.annotation.Resource;

import cn.hutool.core.net.NetUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.GameEnum;
import com.ruoyi.game.domain.bo.RoundNoBO;
import com.ruoyi.game.schedule.asyn.Pick3LotteryTask;
import com.ruoyi.game.schedule.asyn.Pick3RoundTask;
import com.ruoyi.game.schedule.asyn.WingoLotteryTask;
import com.ruoyi.game.schedule.asyn.WingoRoundTask;
import com.ruoyi.game.service.ILotteryService;
import com.ruoyi.game.service.IRoundService;
import cn.hutool.core.util.ObjectUtil;

@Component
public class RoundScheduledTask {
    @Resource
    private IRoundService roundService;

    @Resource
    private ILotteryService lotteryService;

    @Resource
    private RedisCache redisCache;

    @Resource(name = "asyncPick3Executor")
    private ThreadPoolTaskExecutor asyncPick3Executor;

    @Resource(name = "asyncWingoExecutor")
    private ThreadPoolTaskExecutor asyncWingoExecutor;

    /**
     * 判断系统是否windows
     */
    private static final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");


//    public  void main(String[] args) {
//        Queue<Runnable> taskQueue = new LinkedList<>();
//        // 添加任务到队列
//        taskQueue.offer(getWingoRoundTask());
//        taskQueue.offer(getWingoLotteryTask());
//        // 执行队列中的任务
//        while (!taskQueue.isEmpty()) {
//            Runnable task = taskQueue.poll();
//            if (task != null) {
//                task.run();
//            }
//        }
//    }

    /**
     * 时间触发器，每秒触发一次
     */
    @Scheduled(fixedDelay = 1000,fixedRate = -1)
    public void timeWheel(){
//        if(isWindows){
//            return;
//        }



        Calendar  calendar = Calendar.getInstance();
        long  nowSecond = Calendar.getInstance().get(Calendar.SECOND);
        if (nowSecond!=57){
            return;
        }
        System.out.println("lockKey_1");
        String lockKey = "lock:RoundScheduledTask.timeWheel";
        boolean flag = redisCache.tryLock(lockKey,1000);
        if(!flag){
            System.out.println("lockKey_2");
            return;
        }
        System.out.println("lockKey_3");
        try {
            RoundNoBO roundNoBO =roundService.getRoundNo(1,60);
            lotteryService.statWingo(roundNoBO.getRoundNo(),60);

//            int currentMinute = calendar.get(Calendar.MINUTE);
//            if ((currentMinute % 3) == 0) {
//                roundNoBO =roundService.getRoundNo(1,180);
//                lotteryService.statWingo(roundNoBO.getRoundNo(),180);
//
//            }
//            if ((currentMinute % 5) == 0 ) {
//                roundNoBO =roundService.getRoundNo(1,300);
//                lotteryService.statWingo(roundNoBO.getRoundNo(),300);
//
//            }
//            if ((currentMinute % 10) == 0 ) {
//                roundNoBO =roundService.getRoundNo(1,600);
//                lotteryService.statWingo(roundNoBO.getRoundNo(),600);
//
//            }
//            // 获取wingo场次任务
//            List<Runnable> wingoRoundTasks = getWingoRoundTask();
//            // 获取wingo开奖任务
//            List<Runnable> wingoLotteryTasks = getWingoLotteryTask();
//            // 获取pick3场次任务
//            List<Runnable> pick3RoundTasks = getPick3RoundTask();
//            // 获取pick3开奖任务
//            List<Runnable> pick3LotteryTasks = getPick3LotteryTask();
//
//            // 运行任务
//            List<Runnable> wingoTasks = new ArrayList<>();
//            wingoTasks.addAll(wingoRoundTasks);
//            wingoTasks.addAll(wingoLotteryTasks);
//            runWingoTasks(wingoTasks);
//
//            List<Runnable> pick3Tasks = new ArrayList<>();
//            pick3Tasks.addAll(pick3RoundTasks);
//            pick3Tasks.addAll(pick3LotteryTasks);
//            //runPick3Tasks(pick3Tasks);

        }finally {
            redisCache.releaseLock(lockKey);
        }
    }

    /**
     * 执行任务
     * @param tasks
     */
    private void runPick3Tasks(List<Runnable> tasks){
        for(Runnable task : tasks){
            asyncPick3Executor.execute(task);
        }
    }

    /**
     * 执行任务
     * @param tasks
     */
    private void runWingoTasks(List<Runnable> tasks){
        for(Runnable task : tasks){
            asyncWingoExecutor.execute(task);
        }
    }

    /**
     * 获取wingo场次任务
     * @return
     */
    private List<Runnable> getWingoRoundTask() {
        List<Runnable> wingoRoundTasks = new ArrayList<>();
        for(GameEnum.TimeLimitEnum item : GameEnum.TimeLimitEnum.values()){
            WingoRoundTask wingoRoundTask = new WingoRoundTask(roundService,item.getTime());
            wingoRoundTasks.add(wingoRoundTask);
        }
        return wingoRoundTasks;
    }

    /**
     * 获取pick场次任务
     * @return
     */
    private List<Runnable> getPick3RoundTask() {
        List<Runnable> pick3RoundTasks = new ArrayList<>();
        for(GameEnum.TimeLimitEnum item : GameEnum.TimeLimitEnum.values()){
            Pick3RoundTask pick3RoundTask = new Pick3RoundTask(roundService,item.getTime());
            pick3RoundTasks.add(pick3RoundTask);
        }
        return pick3RoundTasks;
    }

    /**
     * 获取wingo开奖任务
     * @return
     */
    private List<Runnable> getWingoLotteryTask(){
        List<Runnable> wingoLotteryTasks = new ArrayList<>();
        for(GameEnum.TimeLimitEnum item : GameEnum.TimeLimitEnum.values()){
            // 获取待开奖队列
            String waitOpenCacheKey = String.format(CacheConstants.GAME_WAIT_OPEN_ROUND_LIST_KEY,GameEnum.GameTypeEnum.WINGO.getType(),item.getTime());
            Object roundObj = redisCache.leftPop(waitOpenCacheKey);
            if(ObjectUtil.isNull(roundObj)){
                continue;
            }
            RoundNoBO roundNoBO = (RoundNoBO) roundObj;
            if(roundNoBO.getEndTime() > System.currentTimeMillis()){
                System.out.println("当前时间:"+System.currentTimeMillis()+",待开奖时间:"+roundNoBO.getEndTime()+",未到开奖时间");
                continue;
            }
            WingoLotteryTask wingoLotteryTask = new WingoLotteryTask(lotteryService,roundNoBO.getRoundNo());
            wingoLotteryTasks.add(wingoLotteryTask);
        }
        return wingoLotteryTasks;
    }

    /**
     * 获取pick3开奖任务
     * @return
     */
    private List<Runnable> getPick3LotteryTask(){
        List<Runnable> pick3LotteryTasks = new ArrayList<>();
        for(GameEnum.TimeLimitEnum item : GameEnum.TimeLimitEnum.values()){
            // 获取待开奖队列
            String waitOpenCacheKey = String.format(CacheConstants.GAME_WAIT_OPEN_ROUND_LIST_KEY,GameEnum.GameTypeEnum.PICK3.getType(),item.getTime());
            Object roundObj = redisCache.leftPop(waitOpenCacheKey);
            if(ObjectUtil.isNull(roundObj)){
                continue;
            }
            RoundNoBO roundNoBO = (RoundNoBO) roundObj;
            Pick3LotteryTask pick3LotteryTask = new Pick3LotteryTask(lotteryService,roundNoBO.getRoundNo());
            pick3LotteryTasks.add(pick3LotteryTask);
        }
        return pick3LotteryTasks;
    }
}
